package com.mti.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.mti.dao.dto.OrganizationDto;
import com.mti.service.CacheableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.server.ServerWebExchange;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mti.configuration.SystemConfig;
import com.mti.dao.model.KmZdryZrbmEntity;
import com.mti.dao.model.SysDictEntity;
import com.mti.dao.qo.TypeQO;
import com.mti.enums.RoleType;
import com.mti.exception.BusinessException;
import com.mti.jwt.AccountBo;
import com.mti.jwt.RequestUtils;
import com.mti.mapper.SysDictMapper;
import com.mti.service.ISysDictService;
import com.mti.service.KmZdryZrbmService;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yangsp
 * @since 2019-04-29
 */
@Service
@CacheConfig(cacheNames = "SysDictCacheable")
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDictEntity> implements ISysDictService {
    @Resource
    private SysDictMapper sysDictMapper;
    
	@Autowired
	private RequestUtils requestUtils;

	@Autowired
	private KmZdryZrbmService  kmZdryZrbmService;
	
	@Autowired
	private RestTemplate restTemplate;
	
	@Autowired
	private SystemConfig systemConfig;

	@Autowired
	private CacheableService cacheableService;
    /**
     *  通过类型获取数据字典
     * @param type
     *     重点人员分类	kp_category
     *     重点人员负责部门	kp_department
     *     重点时期	kp_period
     *     重点人员管控状态	kp_control_state
     *     重点人员管控手段	kp_control_type
     *     重点人员级别	kp_level
     *     重点人员报警方式	kp_alarm_mode
     *     辖区	kp_area
     * @return
     */
	//@Cacheable(key = "#root.method+'('+#type+')'")
    public List<SysDictEntity> getByType(String type) {

        if(StringUtils.isEmpty(type)){
           return null;
        } else {
            LambdaQueryWrapper<SysDictEntity> wrapper = new QueryWrapper<SysDictEntity>().lambda();
            wrapper = wrapper.eq(SysDictEntity::getType,type).eq(SysDictEntity::getDelete,"0");
            wrapper.orderByAsc(SysDictEntity::getSort);
			List<SysDictEntity> list = this.list(wrapper);
			if(null != list && list.size() > 0){
				for(SysDictEntity sysDictEntity : list){
					String key = sysDictEntity.getKey();
					if(null == key || key == ""){
						continue;
					}
					LambdaQueryWrapper<SysDictEntity> wrapper1 = new QueryWrapper<SysDictEntity>().lambda();
					wrapper1 = wrapper1.eq(SysDictEntity::getType,key).eq(SysDictEntity::getDelete,"0");
					wrapper1.orderByAsc(SysDictEntity::getSort);
					List<SysDictEntity> listChildren = this.list(wrapper1);
					sysDictEntity.setChildren(listChildren);
				}
			}
			return list;
        }
    }

    @Cacheable(key = "#root.method+'('+#type+')'")  //精研技术，合并方法
    public String getByTypeRedis(String type){
		if(StringUtils.isEmpty(type)){
			return null;
		} else {
			LambdaQueryWrapper<SysDictEntity> wrapper = new QueryWrapper<SysDictEntity>().lambda();
			wrapper = wrapper.eq(SysDictEntity::getType,type).eq(SysDictEntity::getDelete,"0");
			wrapper.orderByAsc(SysDictEntity::getSort);
			return JSON.toJSONString(this.list(wrapper));
		}
	}



	@Cacheable(key = "#root.method+'('+#type+','+#key+')'",cacheManager = "sysDictEntityCacheManager")
    public SysDictEntity getEntityByKey(String type, String key) {
        LambdaQueryWrapper<SysDictEntity> wrapper = new QueryWrapper<SysDictEntity>().lambda();
        wrapper = wrapper.eq(SysDictEntity::getType,type).eq(SysDictEntity::getKey,key).eq(SysDictEntity::getDelete,"0");
        wrapper.orderByAsc(SysDictEntity::getSort);
        return this.getOne(wrapper);
    }

    @Override
    public List<String> getOrgByOid(List<String> oids) {
        return this.baseMapper.getOrgByOid(oids);
    }

    @Override
	@Cacheable(key = "#root.method+'('+#type+','+#key+')'",cacheManager = "sysDictEntityCacheManager")
    public SysDictEntity getDictByTypeAndVal(String type, String key) {
        return this.baseMapper.getDictByTypeAndVal(type, key);
    }

    @Override
    public String getOidByOname(String oname) {
        return this.baseMapper.getOidByOname(oname);
    }

    @Override
    public Map<String, String> getPersonInfoByMjid(String mjid) {
        return this.baseMapper.getPersonInfoByMjid(mjid);
    }

    @Override
    public SysDictEntity queryEntityByKey(String key) {
        List<SysDictEntity> sysDictEntities = this.list(new QueryWrapper<SysDictEntity>().eq("key_",key)
                .eq("delete_","0"));
        if(sysDictEntities.size()>0){
            return sysDictEntities.get(0);
        }
        return null;
    }

    @Override
    public SysDictEntity queryEntityById(String id) {
        SysDictEntity sysDictEntity = this.baseMapper.selectById(id);
        return sysDictEntity;
    }

    @Override
    public List<SysDictEntity> queryAllRyxles() {
        return sysDictMapper.queryAllRyxles();
    }


	@Override
	public List<SysDictEntity> getType(ServerWebExchange exchange ,TypeQO typeQo) {
		/**
		 * 1、（exchange ，流程类型，字典类型）
		 * 警种 新增  --->只查自己的大类小类
		 * 其他不约束
		 * 修改：该条数据的责任部门   派出所，分局、警种 。
		 **/
		AccountBo bo = requestUtils.getCurrentUser(exchange);
     	if(bo==null) {
     		throw new BusinessException(10019,"此账号已在别处登录，请查证");
     	}
     	String role = bo.getRoleList().get(0).getRoleType();
     	String zrbm = bo.getOrganizationBo().getShortName();
     	String regionId = bo.getOrganizationBo().getId();
     	LambdaQueryWrapper<SysDictEntity> wrapper = new QueryWrapper<SysDictEntity>().lambda();
     	wrapper = wrapper.eq(SysDictEntity::getType,typeQo.getType()).eq(SysDictEntity::getDelete,"0");
     	wrapper.orderByAsc(SysDictEntity::getSort);
     	List<SysDictEntity> list= this.list(wrapper);
     	if(("1".equals(typeQo.getFirst())&&role.equals(RoleType.OWNER_REVIEW_DATA.getType()))||("1".equals(typeQo.getFirst())&&role.equals(RoleType.OWNER_ORG_DATA.getType())
     			)) {
			List<OrganizationDto> orgs = cacheableService.getUpOrgById(regionId);
			OrganizationDto org = getOrganizationByCondition(orgs,"支队");

     		LambdaQueryWrapper<KmZdryZrbmEntity> zrbmWrapper = new QueryWrapper<KmZdryZrbmEntity>().lambda();
     		zrbmWrapper = zrbmWrapper.eq(KmZdryZrbmEntity::getZrbm,org.getShortName());
     		/*if(!"kp_rylb".equals(typeQo.getType())) {
     			zrbmWrapper = zrbmWrapper.eq(LfZdryZrbmEntity::getRydlCode,typeQo.getType());
     		}*/
     		List<KmZdryZrbmEntity> zrbmlist= kmZdryZrbmService.list(zrbmWrapper);
     		if(StringUtils.isEmpty(typeQo.getType())){
     			return null;
     		} else {
     			//新增
     			if((role.equals(RoleType.OWNER_REVIEW_DATA.getType()))||
     					(role.equals(RoleType.OWNER_ADMIN_ORG_DATA.getType()))) {
     				List<SysDictEntity> reSysDicList = new ArrayList<SysDictEntity>();
     				List<String> sysDicList = new ArrayList<String>();
     				//只查询自己的大类小类；
     				if("kp_rylb".equals(typeQo.getType())) {
     					for (SysDictEntity sysDictEntity : list) {
     						for (KmZdryZrbmEntity zdryZrbmEntity : zrbmlist) {
     							if(!sysDicList.contains(zdryZrbmEntity.getRydl())) {
     								if(sysDictEntity.getValue().equals(zdryZrbmEntity.getRydl())) {
     									reSysDicList.add(sysDictEntity);
     									sysDicList.add(zdryZrbmEntity.getRydl());
     								}
     							}
     						}
     					}
     					//小类查询
     				}else {
     					for (SysDictEntity sysDictEntity : list) {
     						for (KmZdryZrbmEntity zdryZrbmEntity : zrbmlist) {
     							if(sysDictEntity.getValue().equals(zdryZrbmEntity.getRyxl())) {
     								reSysDicList.add(sysDictEntity);
     							}
     						}
     					}
     				}
     				return reSysDicList;
     			}
     		}
     		
        }
 	return  list ;

	}


	@Override
	public List<Object> queryKeyword(ServerWebExchange exchange, String keyword) {
		List<Object> list = new ArrayList<Object>(); 
		if(StringUtils.isEmpty(keyword)){
	           return null;
	        }  
			AccountBo bo = requestUtils.getCurrentUser(exchange);
			if (bo == null) {
				throw new BusinessException(10019,"此账号已在别处登录，请查证");
			}
			String role=  bo.getRoleList().get(0).getId();
        	QueryWrapper<SysDictEntity> wrapper = new QueryWrapper<>();
        	wrapper.like("value_", keyword);
        	if(role.equals(RoleType.BREACH_REVIEW_DATA.getType())||role.equals(RoleType.BREACH_REVIEW_DATA.getType())) {
        		wrapper.in("type_", new String[]{ "kp_rylb","zdry_yjczlb","kp_gkjb","kp_zrbm"});
        	}else {
        		wrapper.in("type_", new String[]{ "kp_rylb","zdry_yjczlb","kp_zrgkfj","kp_gkjb","kp_zrbm"});
        	}
        	
        	//wrapper.eq("delete", 0);
            wrapper.orderByAsc("sort_");
            list.addAll(this.list(wrapper));
            // 临时表过度
			if (role.equals(RoleType.POLICE_STATION_DATA.getType())) { // 派出所用户
				//检索民警
			        try {
			            Map<String, Object> map = new HashMap<>();
			            map.put("orgId", bo.getOrgId());
			            map.put("personName", keyword);
			            HttpHeaders headers = new HttpHeaders();
			            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
			            String body = JSON.toJSONString(map);
			            HttpEntity<String> requestEntity = new HttpEntity<String>(body, headers);
			            ResponseEntity<String> result = restTemplate.
			                    postForEntity(systemConfig.getSystemServer() + "/api/system/organization/person/querylist", requestEntity, String.class);
			            //postForEntity("http://127.0.0.1:9052/" + "/organization/person/querylist", requestEntity, String.class);
			        //System.out.println(result);
			        if (null != result) {
						if (null != result.getBody()) {
							JSONObject jsonObject = JSONObject.parseObject(result.getBody().toString());
							if (jsonObject.containsKey("data")) {
								List<Map> orgPersons = JSONArray.parseArray(jsonObject.get("data").toString(), Map.class);
								list.addAll(orgPersons);
							}
						}
					}
			        } catch (Exception e1) {
//			            log.error(e.getMessage());
			            throw new BusinessException(10018,e1.getMessage());
			        }
			} else if (role.equals(RoleType.BREACH_REVIEW_DATA.getType())) { // 分局用户
				Map<String, Object> returnMap = new HashMap<>();
				//检索派出所
				//http://10.168.4.197:10001/api/system/organization/getOrgByPId?pId=530102000000
				ResponseEntity result = restTemplate.getForEntity(
						systemConfig.getSystemServer() + "/api/system/organization/getOrgByPId?pId="+bo.getOrgId()+"&orgType=3&keyword="+keyword,
						JSONObject.class);
				//Map<String, String> returnMap = new HashMap<>();
				if (null != result) {
					if (null != result.getBody()) {
						JSONObject obj = JSONObject.parseObject(result.getBody().toString());
						List<Map> res = JSONArray.parseArray(obj.get("data").toString(), Map.class);
						returnMap.put("type", "pcs");
						returnMap.put("pcs", obj.get("data"));
						list.add(returnMap);
					}
				}
			} else  { // 警种用户  和 情报中心
				//检索分局
				/*ResponseEntity result = restTemplate.getForEntity(
						systemConfig.getSystemServer() + "/api/system/organization/getOrgByOrgtype?orgType=2",
						JSONObject.class);
				Map<String, String> returnMap = new HashMap<>();
				if (null != result) {
					if (null != result.getBody()) {
						JSONObject obj = JSONObject.parseObject(result.getBody().toString());
						List<Map> res = JSONArray.parseArray(obj.get("data").toString(), Map.class);
						list.addAll(res);
					}
				}*/
				
			}
			//地址关键字查询
            ResponseEntity result = restTemplate.getForEntity(
					systemConfig.getSystemServer() + "/api/system/region/getByKeyword?keyword="+keyword,
					JSONObject.class);
			Map<String, Object> returnMap = new HashMap<>();
			if (null != result) {
				if (null != result.getBody()) {
					JSONObject obj = JSONObject.parseObject(result.getBody().toString());
					returnMap.put("type", "hjd");
					returnMap.put("address", obj.get("data"));
					list.add(returnMap);
				}
			} 
				
		return list;
	}
	
	@Override
	public List<Object> queryWarnKeyword(ServerWebExchange exchange, String keyword) {
		List<Object> list = new ArrayList<Object>(); 
		if(StringUtils.isEmpty(keyword)){
	           return null;
	        }  
			AccountBo bo = requestUtils.getCurrentUser(exchange);
			if (bo == null) {
				throw new BusinessException(10019,"此账号已在别处登录，请查证");
			}
			//String role=  bo.getRoleList().get(0).getId();
        	QueryWrapper<SysDictEntity> wrapper = new QueryWrapper<>();
        	wrapper.like("value_", keyword);
    		wrapper.in("type_", new String[]{ "kp_rylb","zdry_yjczlb","km_bjfs","kp_gkjb","kp_zrbm","event_status"});
            wrapper.orderByAsc("sort_");
            list.addAll(this.list(wrapper));
            //地址关键字查询
            ResponseEntity result = restTemplate.getForEntity(
					systemConfig.getSystemServer() + "/api/system/region/getByKeyword?keyword="+keyword,
					JSONObject.class);
			Map<String, Object> returnMap = new HashMap<>();
			if (null != result) {
				if (null != result.getBody()) {
					JSONObject obj = JSONObject.parseObject(result.getBody().toString());
					returnMap.put("type", "hjd");
					returnMap.put("address", obj.get("data"));
					list.add(returnMap);
				}
			}
		return list;
	}

	/**
	 * 根据条件查询对应单位
	 * @param organizationDtos
	 * @param con
	 * @return
	 */
	private OrganizationDto getOrganizationByCondition(List<OrganizationDto> organizationDtos,String con){
		OrganizationDto result = null;
		for(OrganizationDto org : organizationDtos){
			if(org.getShortName().indexOf(con)>=0) {
				result = org;
				break;
			}
		}
		return result;
	}

}
